<?php

namespace addons\zzuser\controller\api;

use addons\zzuser\model\UserM;
use addons\zzuser\service\EncryptS;
use app\common\controller\Api;
use think\Validate;

class Login extends Api
{
    protected $noNeedLogin = 'index';

    public function index()
    {
        $validate = new Validate();
        if (!$validate->check(input(), [
            'username' => 'requireIf:mobile,""',
            'mobile'   => 'requireIf:username,""',
            'password' => 'require',
        ])) {
            $this->error($validate->getError());
        }
        $username = input('username');
        $mobile   = input('mobile');
        $password = input('password');
        if ($username) {
            $query = UserM::where('username', $username);
        } else {
            $query = UserM::where('mobile', $mobile);
        }
        $user = $query->find();
        if ($user) {
            if ($user['password'] == EncryptS::password($password, $user['salt'])) {
                $this->auth->direct($user['id']);
                $this->success('', [
                    'token' => $this->auth->getToken(),
                ]);
            }
        }
        $this->error();
    }
}
